package com.yulebaby.callsenter.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.MultipleCustomerAdapter;
import com.yulebaby.callsenter.bean.CustomerBean;
import com.yulebaby.callsenter.bean.multiplebean.MultipleCustomerBean;
import com.yulebaby.callsenter.event.RefreshEvent;
import com.yulebaby.callsenter.event.SequenceEvent;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.ResultCallback;
import com.yulebaby.callsenter.task.CustomerDataConformTask;
import com.yulebaby.callsenter.task.RequestCustomerTask;
import com.yulebaby.callsenter.ui.activity.AddPreSaleRemarkActivity;
import com.yulebaby.callsenter.ui.activity.CustomerInfoActivity;
import com.yulebaby.callsenter.ui.base.BaseRecycleViewFragment;
import com.yulebaby.callsenter.ui.view.CallDialog;
import com.yulebaby.callsenter.ui.view.CustomPopwindow;
import com.yulebaby.callsenter.utils.DiffUtils;
import com.yulebaby.callsenter.utils.PhoneUtil;
import com.yulebaby.callsenter.utils.ThreadUtils;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * Author: Zhangbo
 * Time: 2016/11/11
 */
public class NewCustomerFragment extends BaseRecycleViewFragment<List<CustomerBean>, MultipleCustomerAdapter> {


    public ArrayList<MultipleCustomerBean> mMultipleCustomerList;
    private MultipleCustomerAdapter mAdapter;
    public ArrayList<String> phoneNumList;
    private CustomPopwindow mCustomPopwindow;
    private MultipleCustomerBean mCustomerBean;
    private CallDialog mCallDialog;
    List<MultipleCustomerBean> mNewDatas;
    private boolean fromInternetRequest;
    private boolean isFromSequenceType = false;
    DiffUtil.DiffResult diffResult = null;

    private int nowSequenceType = SequenceEvent.sequenceByTime;
    private int clickPosition = -1;


    public static NewCustomerFragment newInstance() {
        Bundle args = new Bundle();
        NewCustomerFragment fragment = new NewCustomerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void requestData() {
        int requestType = nowSequenceType == SequenceEvent.sequenceByTime ? SequenceEvent.sequenceByTime : SequenceEvent.sequenceByLevel;
        RequestCustomerTask.doRequestAllCustomer(mActivity, fromInternetRequest, requestType, new ResultCallback<List<CustomerBean>>() {
            @Override
            public void onResult(List<CustomerBean> result) {
                if (fromInternetRequest) {
                    fromInternetRequest = false;
                    requestData(); //有效率问题
                } else {
                    processResult(result);
                }
            }
        });
    }

    /**
     * 处理数据
     *
     * @param result
     */
    private void processAddResult(final List<CustomerBean> result) {
        if (result != null) {
            if (result.size() > 0) {
                ThreadUtils.runOnBackgroundThread(new Runnable() {
                    @Override
                    public void run() {
                        mNewDatas.clear();
                        mNewDatas = CustomerDataConformTask.doCustomerDataConform(result);
                        diffResult = DiffUtil.calculateDiff(new DiffUtils(mMultipleCustomerList, mNewDatas), true);
                        ThreadUtils.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                diffResult.dispatchUpdatesTo(mAdapter);
                                mMultipleCustomerList.clear();
                                mMultipleCustomerList.addAll(mNewDatas);
                                if (isFromSequenceType) {
                                    mRecyclerView.scrollToPosition(0);
                                    isFromSequenceType = false;
                                }
                                mStateViewLayout.showSuccessView();
                                if (isRefreshing()) {
                                    refreshComplete();
                                }
                            }
                        });
                    }
                });
            } else {
//                ToastUtil.showToast("您现在还没有客户!");
            }
        } else {
            mStateViewLayout.showErrorView();
        }
    }

    /**
     * 接受刷新信息的请求
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshEvent(RefreshEvent event) {
        if (event != null) {
            fromInternetRequest = event.getRefreshType() == RefreshEvent.refreshDataFromInternet;
            onRefresh();
        }
    }

    /**
     * 对排序方式进行处理
     *
     * @param typeEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void sequenceCustomer(SequenceEvent typeEvent) {
        if (typeEvent.getSequenceType() == SequenceEvent.sequenceByTime && nowSequenceType != typeEvent.getSequenceType()) {
            nowSequenceType = SequenceEvent.sequenceByTime;
            isFromSequenceType = true;
            requestData();
        } else if (typeEvent.getSequenceType() == SequenceEvent.sequenceByLevel && nowSequenceType != typeEvent.getSequenceType()) {
            nowSequenceType = SequenceEvent.sequenceByLevel;
            isFromSequenceType = true;
            requestData();
        }
    }


    /**
     * 处理结果
     *
     * @param result
     */

    private void processResult(List<CustomerBean> result) {
        if (result != null) {
            if (result.size() == 0 && mMultipleCustomerList.size() == 0) {
                ToastUtil.showToast("您现在还没有客户!");
            } else if (result.size() == 0 && mMultipleCustomerList.size() == 2) {
                mMultipleCustomerList.clear();
            }
            if (result.size() > 0) {
                mMultipleCustomerList.clear();
                List<MultipleCustomerBean> beanList = CustomerDataConformTask.doCustomerDataConform(result);
                mMultipleCustomerList.addAll(beanList);
            }
            mStateViewLayout.showSuccessView();
            mAdapter.notifyDataSetChanged();
            if (isFromSequenceType) {
                mRecyclerView.scrollToPosition(0);
                isFromSequenceType = false;
            }
            if (isRefreshing()) {
                refreshComplete();
            }
        } else {
            mStateViewLayout.showErrorView();
        }
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mNewDatas = new ArrayList<>();
        mMultipleCustomerList = new ArrayList<>();
        phoneNumList = new ArrayList<>();
        mAdapter = new MultipleCustomerAdapter(mMultipleCustomerList);
        requestData();
        mRecyclerView.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                int itemType = ((MultipleCustomerBean) adapter.getItem(position)).getItemType();
                if (itemType == MultipleCustomerBean.CUSTOMERITEM) {
                    //使用Intent的方式  使用消息总线的方式改进  粗糙版本
                    Intent intent = new Intent(mActivity, CustomerInfoActivity.class);
                    intent.putExtra(Constant.CUSTOMER_BEAN, ((MultipleCustomerBean) adapter.getItem(position)).getCustomerBean());
                    clickPosition = position;
                    intent.putExtra(Constant.IS_MODIFY, true);
                    startActivityForResult(intent, REQUEST_LOOKOVER_INFO);
                }
            }

            @Override
            public void onItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int position) {
                mCustomerBean = (MultipleCustomerBean) baseQuickAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.iv_robcustomer:
                        //选择前清空一下集合
                        phoneNumList.clear();
                        checkHasPhoneNum(mCustomerBean.getCustomerBean());
                        switchCallNum();
                        break;
                    case R.id.tv_addtrack://添加售前跟踪
                        Intent addintent = new Intent(mActivity, AddPreSaleRemarkActivity.class);
                        addintent.putExtra(Constant.CUSTOMER_BEAN, mCustomerBean.getCustomerBean());
                        startActivity(addintent);
                        break;

                    case R.id.tv_looktrack://查看跟踪记录
                        if (mCustomerBean.getCustomerBean() != null) {
                            initCustomPopwindow(view);
                        }
                        break;
                }
            }
        });
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_LOOKOVER_INFO && resultCode == RESULT_OK && data != null) {
/*            CustomerBean bean = (CustomerBean) data.getSerializableExtra(Constant.CUSTOMER_BEAN);
            if (clickPosition != -1) {
                mMultipleCustomerList.remove(clickPosition);
                mMultipleCustomerList.add(clickPosition, new MultipleCustomerBean(MultipleCustomerBean.CUSTOMERITEM, bean));
                mAdapter.notifyItemChanged(clickPosition);
            }*/
        }
    }

    /**
     * 初始化Popwindow
     *
     * @param view
     */
    private void initCustomPopwindow(View view) {
        mCustomPopwindow = new CustomPopwindow(mActivity, itemsOnClick, mCustomerBean.getCustomerBean());
        mCustomPopwindow.showAtLocation(view,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    //为弹出窗口内部实现监听类
    private View.OnClickListener itemsOnClick = new View.OnClickListener() {

        public void onClick(View v) {
            mCustomPopwindow.backgroundAlpha(mActivity, 1f);
            switch (v.getId()) {
                case R.id.ib_cancal:
                    if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
                        mCustomPopwindow.dismiss();
                    }
                    break;
            }
        }

    };

    /**
     * 选择想要拨打的电话号码
     */
    private void switchCallNum() {
        if (phoneNumList.size() == 1) {
            PhoneUtil.callPhones(phoneNumList.get(0));
        } else {
            mCallDialog = new CallDialog(mActivity, phoneNumList, mCustomerBean.getCustomerBean());
            mCallDialog.setNumListener(new CallDialog.selectNumListener() {
                @Override
                public void selectNum(String num) {
                    PhoneUtil.callPhones(num);
//                    mCustomerBean.setRecent_call(1);
//                    Dao.getInstance().updateBean(mCustomerBean);
                }
            });
            mCallDialog.show();
        }
    }

    /**
     * 检查是否包含备用号码
     *
     * @param customerBean
     */
    private void checkHasPhoneNum(CustomerBean customerBean) {
        String phone = customerBean.getPhone();
        String spare_phone1 = customerBean.getSpare_phone1();
        String spare_phone2 = customerBean.getSpare_phone2();
        phoneNumList.add(phone);
        if (!TextUtils.isEmpty(spare_phone1)) {
            phoneNumList.add(spare_phone1);
        }
        if (!TextUtils.isEmpty(spare_phone2)) {
            phoneNumList.add(spare_phone2);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mCustomPopwindow != null && mCustomPopwindow.isShowing()) {
            mCustomPopwindow.dismiss();
        }

    }

    /**
     * 有点问题 以后封装处理 TODO
     *
     * @param result
     * @return
     */
    @Override
    protected MultipleCustomerAdapter getRecycleAdapt(List<CustomerBean> result) {
        return null;
    }

}
